<template>
	<!-- custom-btn 自定义上传图片按钮 -->
	<u-upload 
	ref="ossUpload"
	:action="action" 
	:auto-upload="true" 
	:max-size="5 * 1024 * 1024"
	:before-upload="beforeUpload"
	:show-progress="false"
	:form-data="formDate"
	:preview-full-image="false"
	:deletable="false"
	:show-upload-list="false"
	:custom-btn="true"
	max-count="1"
	@on-success="uploadSucess"
	>
		<u-avatar slot="addBtn" :src="avatar_url" size="140"></u-avatar>
	</u-upload>
</template>

<script>
	let _this = {}
	export default {
		name:"oss-upload",
		data() {
			return {
				avatar_url: '',// 头像地址,自定义预览时使用
				action: 'http://www.example.com/upload',
				formDate: {},
				upFileName: '',
				lists: []
			};
		},
		created() {
			_this = this;
		},
		methods:{
			async beforeUpload(index, list) {
				// 获取OSS token并自动上传
				const ossToken = await _this.$u.api.authOssToken()
				_this.action = ossToken.host;
				
				const {file} = list[0]
				let fileName = ''
				// #ifdef H5
				fileName = file.name;
				// #endif
				// #ifndef H5
				fileName = file.path;
				// #endif
				_this.upFileName = _this.$u.guid(20) + fileName.slice(fileName.lastIndexOf('.'))
				_this.formDate = {
					'key' : _this.upFileName,
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessid, 
					'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					'signature': ossToken.signature,
				};
				
				// 自定义预览列表,上传成功时
				const {url,error,progress} = _this.$refs.ossUpload.lists[0];
				if(!error){
					_this.avatar_url = url;
				}
				
				return true;
			},
			async uploadSucess(){
				_this.$refs.ossUpload.remove(0)
				// 请求API，更新客户头像
				await _this.$u.api.updateUserAvatar({avatar: _this.upFileName})
				
				// 刷新缓存的客户信息
				_this.$u.utils.refreshUserInfo()
				
			}
		},
		mounted() {
			// 组件挂载时，设置头像地址。
			_this.avatar_url = _this.vuex_user.avatar_url
		}
	}
</script>

<style>

</style>
